﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OrmSmackdown.EntityFrameworks.Mappings;

namespace OrmSmackdown.EntityFrameworks
{
    public class Crud : ICrud
    {
        private OrmSmackdown.EntityFrameworks.Mappings.efSmackDownEntities _ctx;

        public Crud(string connectionInformation)
        {
            _ctx = new OrmSmackdown.EntityFrameworks.Mappings.efSmackDownEntities(connectionInformation);
        }

        public int Create(string firstName, string lastName, string email)
        {
            var person = new Mappings.Contact() { FirstName = firstName, LastName = lastName, Email = email };

            _ctx.AddToPeople(person);

            _ctx.SaveChanges();

            return person.PersonId;
        }

        public IPerson Read(int id)
        {
            return _ctx.People.OfType<Mappings.Contact>().Where(p => p.PersonId == id).FirstOrDefault();
        }

        public void Update(int id, string firstName, string lastName, string email)
        {
            var person = _ctx.People.Where(p => p.PersonId == id).FirstOrDefault();
            person.FirstName = firstName;
            person.LastName = lastName;
            person.Email = email;
            _ctx.SaveChanges();            
        }

        public void Delete(int id)
        {
            var person = _ctx.People.Where(p => p.PersonId == id).FirstOrDefault();
            _ctx.DeleteObject(person);
            _ctx.SaveChanges();
        }

        public void Dispose()
        {
            _ctx.Dispose();
        }
    }
}
